package org.carabiner.infinitest;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.carabiner.infinitest.depgraph.ClassFileFilter;
import org.carabiner.infinitest.depgraph.JavaClass;

public class FileChangeDetector
{
  private File classDir;
  private Map<File,Long> timestampIndex;  
  
  public FileChangeDetector(File classFileDirectory)
  {
    classDir = classFileDirectory;
    timestampIndex = new HashMap<File, Long>();
  }
  
  public Set<File> findChangedFiles() throws IOException
  {
    return findFiles(classDir);
  }
  
  private Set<File> findFiles(File classfileOrDirectory) throws IOException
  {    
    Set<File> changedFiles = new HashSet<File>();
    if (classfileOrDirectory.isDirectory())
    {
      File[] children = classfileOrDirectory.listFiles(new ClassFileFilter());
      for(int i = 0; i < children.length; i++)
      {
        changedFiles.addAll(findFiles(children[i]));
      }
    }
    else
    {
      if (ClassFileFilter.isClassFile(classfileOrDirectory))
      {        
        Long timestamp = timestampIndex.get(classfileOrDirectory);
        if (timestamp == null || classfileOrDirectory.lastModified() != timestamp)
        {
          timestampIndex.put(classfileOrDirectory, classfileOrDirectory.lastModified());
          changedFiles.add(classfileOrDirectory);
        }        
      }
    }
    return changedFiles;
  }

  public void clear()
  {
    timestampIndex.clear();
  }

}
